<?php

namespace App\Http\Controllers\API;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use \App\model\mongodb;

class GetTheData extends Controller
{
    //
    private $mongodb;

    public function __construct(){
    	date_default_timezone_set("Asia/Shanghai");
    }

    public function getTheData(Request $request){
    	$post = $request->json()->all();

        $inpage = env('APP_INPAGE', 10);

    	$searchParameter = array('sender', 'getter', 'type', 'page');
    	foreach ($searchParameter as $key => $value) {
    		if (!isset($post[$value])) {
    			$error['code'] = 0;
    			$error['reason'] = 'Need more key : ' . $value;
    			return $error;
    		}
    	}
    	foreach ($post as $key => $value) {
    		if (!in_array($key, $searchParameter)) {
    			$error['code'] = 0;
    			$error['reason'] = 'There\'s a illegal parameter : '.$key;
    			return $error;
    		}
    	}

        $this->mongodb = mongodb::connectionMongodb('dialog',$post['sender'].$post['getter']);

        $datas = Redis::LRANGE($post['sender'].$post['getter'].$post['type'], 0, -1);
        $count = $inpage - count($datas);
        $databaseData = $this->mongodb->skip(($post['page'] - 1) * $inpage - $count)->take($count)->orderBy('time', 'desc')->get()->toArray();
        $unin = $datas;
        foreach ($databaseData as $key => $value) {
            unset($value['_id']);
            array_push($unin, json_encode($value));
        }
        if (count($unin) > $post['page'] * $inpage) {
            $for = count($unin);
            for ($i = 0;$for >= $i; $i ++) {
                if ($i < $post['page'] * $inpage) {
                    array_shift($unin);
                }
            }
        }
    	$result = array();
        foreach ($unin as $key => $value) {
            $result[count($unin)-1-$key] = $value;
        }
        foreach ($result as $key => $value) {
            $unin[$key] = $result[$key];
        }
        return json_encode($unin);
    }
}
